<template>
  <div class="post-page">
    <el-card shadow="never" class="toolbar">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <span class="title">社区讨论</span>
        <el-button 
          v-if="userStore.user" 
          type="primary" 
          @click="handleAddPost"
        >
          发布帖子
        </el-button>
      </div>
    </el-card>

    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="搜索">
          <el-input 
            v-model="searchForm.searchText" 
            placeholder="搜索标题或内容"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="searchForm.tags"
            multiple
            filterable
            allow-create
            placeholder="选择标签"
            style="width: 300px"
            clearable
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 帖子列表 -->
    <el-card shadow="never" class="list-card">
      <div v-loading="loading">
        <div v-if="postList.length === 0" class="empty-state">
          <el-empty description="暂无帖子" />
        </div>
        <div v-else>
          <div 
            v-for="post in postList" 
            :key="post.id" 
            class="post-item"
            @click="goPostDetail(post.id!)"
          >
            <div class="post-header">
              <div class="post-title">{{ post.title }}</div>
              <div class="post-actions" @click.stop>
                <el-button 
                  v-if="userStore.user?.id === post.userId" 
                  type="text" 
                  size="small"
                  @click.stop="handleEditPost(post)"
                >
                  编辑
                </el-button>
                <el-button 
                  v-if="userStore.user?.id === post.userId || isAdmin" 
                  type="text" 
                  size="small"
                  danger
                  @click.stop="handleDeletePost(post.id!)"
                >
                  删除
                </el-button>
              </div>
            </div>
            <div class="post-content">{{ getPreviewContent(post.content) }}</div>
            <div class="post-footer">
              <div class="post-meta">
                <el-avatar :src="post.user?.userAvatar" size="small" />
                <span class="username">{{ post.user?.userName || '匿名用户' }}</span>
                <span class="time">{{ formatTime(post.createTime) }}</span>
              </div>
              <div class="post-tags">
                <el-tag 
                  v-for="(tag, i) in post.tagList" 
                  :key="i" 
                  size="small"
                  style="margin-right: 6px"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="post-stats">
                <span><el-icon><Star /></el-icon> {{ post.thumbNum || 0 }}</span>
                <span><el-icon><Collection /></el-icon> {{ post.favourNum || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑帖子对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="70%"
      :close-on-click-modal="false"
    >
      <PostForm
        v-if="dialogVisible"
        :post="editingPost"
        @submit="handleFormSubmit"
        @cancel="dialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Collection } from '@element-plus/icons-vue'
import { PostControllerService } from '../../../generated'
import type { PostVO, PostAddRequest, PostEditRequest, PostQueryRequest, DeleteRequest } from '../../../generated'
import { useUserStore } from '../../stores/user.ts'
import PostForm from './PostForm.vue'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

// 判断是否是管理员
const isAdmin = computed(() => {
  return userStore.user?.userRole === 'admin'
})

// 列表数据
const loading = ref(false)
const postList = ref<PostVO[]>([])
const total = ref(0)
const pageSize = 10
const currentPage = ref(1)

// 搜索表单
const searchForm = ref<PostQueryRequest>({
  searchText: '',
  tags: [],
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('发布帖子')
const editingPost = ref<PostVO | null>(null)

// 常用标签
const commonTags = ['提问', '分享', '讨论', '求助', '经验', '教程']

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const request: PostQueryRequest = {
      current: currentPage.value,
      pageSize,
      searchText: searchForm.value.searchText,
      tags: searchForm.value.tags,
    }
    const res = await PostControllerService.listPostVoByPage(request)
    if (res.code === 0 && res.data) {
      postList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取帖子列表失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPosts()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchPosts()
}

const handleReset = () => {
  searchForm.value = {
    searchText: '',
    tags: [],
  }
  currentPage.value = 1
  fetchPosts()
}

const goPostDetail = (id: number) => {
  router.push({ name: 'PostDetail', params: { id } })
}

const handleAddPost = () => {
  if (!userStore.user) {
    ElMessage.warning('请先登录')
    router.push('/user/login')
    return
  }
  editingPost.value = null
  dialogTitle.value = '发布帖子'
  dialogVisible.value = true
}

const handleEditPost = (post: PostVO) => {
  editingPost.value = post
  dialogTitle.value = '编辑帖子'
  dialogVisible.value = true
}

const handleDeletePost = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const request: DeleteRequest = { id }
    const res = await PostControllerService.deletePost(request)
    
    if (res.code === 0) {
      ElMessage.success('删除成功')
      fetchPosts()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleFormSubmit = async (formData: PostAddRequest | PostEditRequest) => {
  try {
    if (editingPost.value) {
      // 编辑
      const editRequest: PostEditRequest = {
        id: editingPost.value.id,
        ...formData,
      }
      const res = await PostControllerService.editPost(editRequest)
      if (res.code === 0) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchPosts()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加
      const res = await PostControllerService.addPost(formData as PostAddRequest)
      if (res.code === 0) {
        ElMessage.success('发布成功')
        dialogVisible.value = false
        fetchPosts()
      } else {
        ElMessage.error(res.message || '发布失败')
      }
    }
  } catch (e) {
    ElMessage.error('操作失败')
  }
}

const getPreviewContent = (content?: string) => {
  if (!content) return ''
  // 移除 markdown 标记，只显示纯文本预览
  const text = content.replace(/[#*`\[\]()]/g, '').trim()
  return text.length > 200 ? text.substring(0, 200) + '...' : text
}

const formatTime = (time?: string) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

onMounted(fetchPosts)
</script>

<style scoped>
.post-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
}

.toolbar {
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.search-card {
  margin-bottom: 12px;
}

.list-card {
  padding-bottom: 8px;
}

.post-item {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.post-item:hover {
  background-color: #f5f7fa;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.post-content {
  color: #606266;
  margin-bottom: 12px;
  line-height: 1.6;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
}

.username {
  margin-right: 12px;
}

.time {
  color: #c0c4cc;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.post-stats {
  display: flex;
  gap: 16px;
  color: #909399;
  font-size: 14px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.pagination {
  margin-top: 16px;
  text-align: center;
}
</style>